class PaymentRequest < ApplicationRecord
  belongs_to :klass, foreign_key: :academic_partition_id
  belongs_to :plan, counter_cache: true

  has_one :order
  has_many :order_histories

  validates :student_name, uniqueness: { scope: [:academic_partition_id, :plan_id], message: '学生已存在' },
                           length: { minimum: 2, maximum: 50, message: '学生姓名长度应在2至50字符之间' }

  delegate :grade, to: :klass
  delegate :department, to: :grade
  delegate :college, to: :department

  scope :paid, ->(paid) {
    next all if paid.nil?
    if paid
      where('orders.state': 'succeeded')
    else
      where('orders.state is null or orders.state != ?', 'succeeded')
    end
  }

  def paid?
    !!(order && order.succeeded?)
  end
end
